# 添加input目录
import sys
sys.path.append('../input') 

# from ssqmodule.utils import show
# show()

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense,SimpleRNN,Embedding
import matplotlib.pyplot as plt
import os
from ssqmodule.utils import get_ssq_db,get_windex_to_w


# input_word='abcdefghijklmnopqrstuvwxyz'
# w_to_id=get_ssq_all()

ssq_all_count=17721088
# training_set_scaled=[i for i in range(0,17721088)]

x_train=[]
y_train=[]

ssq_db_lst=get_ssq_db()  #数据库中所有的双色球历史数据

for i in range(4,len(ssq_db_lst)):
    x_train.append(ssq_db_lst[i-4:i])
    y_train.append(ssq_db_lst[i])

np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
tf.random.set_seed(7)

# Embedding输入要求[送入样本数,循环核时间展开步数]
x_train=np.reshape(x_train, (len(x_train),4))
y_train=np.array(y_train)

model=tf.keras.Sequential([
    Embedding(ssq_all_count,2),
    SimpleRNN(10),
    Dense(ssq_all_count,activation='softmax')
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

# print(os.path.dirname(os.path.abspath("checkpoint/rnn_onhot.ckpt")))
checkpoint_save_path=os.path.abspath("checkpoint/ssq_4pre1.ckpt")
print(checkpoint_save_path)
if os.path.exists(checkpoint_save_path+'.index'):
    print('-------------------load the model-------------------')
    model.load_weights(checkpoint_save_path)

cp_callback=tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                save_weights_only=True,
                                                save_best_only=True,
                                                monitor='loss')       

history=model.fit(x_train,y_train,batch_size=32,epochs=100,callbacks=[cp_callback])
model.summary()

file=open('./weights_ssq_4pre1.txt','w')
for v in model.trainable_variables:
    file.write(str(v.name)+'\n')
    file.write(str(v.shape)+'\n')
    file.write(str(v.numpy())+'\n')
file.close()

#显示训练集和验证集的acc和loss曲线
acc=history.history['sparse_categorical_accuracy']
loss=history.history['loss']

plt.subplot(1,2,1)
plt.plot(acc,label='训练集的accuracy')
plt.title('训练集的accuracy')
plt.legend()

plt.subplot(1,2,2)
plt.plot(loss,label='训练集的loss')
plt.title('训练集的loss')
plt.legend()

plt.show()

#预测值
preNum=input("输入当前期号：") or '2023101'
predict_lst=get_ssq_lishi_by_qihao(preNum)

predict_lst=np.reshape(predict_lst, [1,4])
result=model.predict([predict_lst])
pred=tf.argmax(result,axis=1)
pred=int(pred)
tf.print('期号：'+preNum+'预测为->'+get_windex_to_w(pred))
